﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Security.Principal;

public partial class Tools_ContentUploadX : System.Web.UI.Page
{
	protected override void OnError(EventArgs e)
	{
		if (Server.GetLastError() is HttpException)
		{
			string js = "window.parent.onComplete('error', '" + Resources.DatabaseStrings.FileSizeUpload + " " + Resources.DatabaseStrings.FileSizeUploadBig + "');";
			ScriptManager.RegisterStartupScript(this, typeof(Tools_ContentUploadX), "progress", js, true);

			Server.ClearError();

			Session["UploadError"] = true;
		}
		else
		{
			base.OnError(e);
		}
	}

	private DataSet GetSystemConfigDataSet()
	{
		DataSet ds_SystemConfig = (DataSet)Session["ds_SystemConfig"];
		if (ds_SystemConfig == null)
		{
            ds_SystemConfig = Hipocrate.DB.DBConnection.GetData("System_Config_Select", new string[] { }, new object[] { });
			Session["ds_SystemConfig"] = ds_SystemConfig;
		}
		return ds_SystemConfig;
	}

	protected void Page_Load(object sender, EventArgs e)
	{
		//if (!IsPostBack)
		//{
		//    if (Session["UploadError"] != null)
		//    {
		//        string js = "window.parent.onComplete('error', '" + Resources.DatabaseStrings.FileSizeUpload + " " + Resources.DatabaseStrings.FileSizeUploadBig + "');";
		//        ScriptManager.RegisterStartupScript(this, typeof(Tools_ContentUploadX), "progress", js, true);

		//        Server.ClearError();
		//    }
		//}

		bool bUseImpersonation = false;
		WindowsImpersonationContext impContext = null;

		UploadInfo uploadInfo = this.Session["UploadInfo"] as UploadInfo;
		uploadInfo.IsReady = false;
		string sPath = uploadInfo.Path;

		DataSet ds_SystemConfig = GetSystemConfigDataSet();
		DataView dv = new DataView(ds_SystemConfig.Tables[0]);
		dv.RowFilter = "Code = 'UploadRootPath'";

		string _strRootPath = "";
		if (dv[0]["Name"].ToString().StartsWith("~"))
		{
			bUseImpersonation = false;
			_strRootPath = System.Web.HttpContext.Current.Request.MapPath(dv[0]["Name"].ToString());
		}
		else
		{
			bUseImpersonation = true;
			_strRootPath = dv[0]["Name"].ToString();
		}

		//		string _strRootPath = System.Web.HttpContext.Current.Request.MapPath("~/Tools/Upload");
		//		string _strRootPath = @"\\spetro004004.ww.omv.com\HD\NOB\FSMS";
		System.Web.HttpFileCollection _files = System.Web.HttpContext.Current.Request.Files;
		System.Text.StringBuilder _message = new System.Text.StringBuilder(Resources.DatabaseStrings.FileUploaded + "<br>");

		try
		{
			if (this.IsPostBack)
			{
				//  do some basic validation
				if (this.fileUpload.PostedFile != null && this.fileUpload.PostedFile.ContentLength > 0 && this.fileUpload.PostedFile.ContentLength < 10485760)
				{
					if (bUseImpersonation)
						impContext = ImpersonationHelper.StartImpersonate();
					//  build the local path
					string path = "";
					switch (sPath)
					{
						case "sms": path = _strRootPath;
							break;
						case "xms": path = System.Web.HttpContext.Current.Request.MapPath("~/Tools/TempFiles"); ;
							break;
					};

					string fileName = Path.GetFileName(this.fileUpload.PostedFile.FileName);

					//  build the strucutre and stuff it into session
					uploadInfo.ContentLength = this.fileUpload.PostedFile.ContentLength;
					uploadInfo.FileName = fileName;
					uploadInfo.UploadedLength = 0;

					//  todo: execute any special logic if the file already exists ...

					//  let the polling process know that we are done initializing ...
					uploadInfo.IsReady = true;
					uploadInfo.filePath = "~/Tools/Upload/" + fileName;
					uploadInfo.strfilePath = _strRootPath + @"\" + fileName;
					int bufferSize = 1;
					byte[] buffer = new byte[bufferSize];

					//  write and save the bytes to disk
					using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
					{
						while (uploadInfo.UploadedLength < uploadInfo.ContentLength)
						{
							int bytes = this.fileUpload.PostedFile.InputStream.Read(buffer, 0, bufferSize);
							fs.Write(buffer, 0, bytes);
							uploadInfo.UploadedLength += bytes;
						}
					}

					if (bUseImpersonation)
						ImpersonationHelper.StopImpersonate(impContext);

					//  let the parent page know we have processed the uplaod
					string js = "window.parent.onComplete('success', '{0} " + Resources.DatabaseStrings.uploadSuccess + "');";
					ScriptManager.RegisterStartupScript(this, typeof(Tools_ContentUploadX), "progress", string.Format(js, fileName), true);
				}
				else
				{
					if (this.fileUpload.PostedFile.ContentLength >= 10485760)
					{
						//  let the parent page know we have processed the uplaod
						string js = "window.parent.onComplete('error', '" + Resources.DatabaseStrings.FileSizeUpload + " " + Resources.DatabaseStrings.FileSizeUploadBig + "');";
						ScriptManager.RegisterStartupScript(this, typeof(Tools_ContentUploadX), "progress", js, true);
					}
					else
					{
						//  let the parent page know we have processed the upload
						const string js = "window.parent.onComplete('error', 'There was a problem with the file.');";
						ScriptManager.RegisterStartupScript(this, typeof(Tools_ContentUploadX), "progress", js, true);
					}
				}

				//  let the webservie know that we are not yet ready
				uploadInfo.IsReady = false;
			}
		}
		catch (Exception ex)
		{
			Tools.ScrieInLog(Server, "ERROR (ContentUploadX.aspx.cs) [SessionID='" + Session.SessionID + "', UserName='" + this.User.Identity.Name + "', ImpersonationHelper.GetCurrentUser='" + ImpersonationHelper.GetCurrentUser() + "']:\r\nMessage: " + ex.Message + "\r\nSource: " + ex.Source + "\r\nTargetSite: " + ex.TargetSite + "\r\nStackTrace: \r\n" + ex.StackTrace + "\r\nStackTrace2: \r\n" + (new System.Diagnostics.StackTrace(true)).ToString());

			string js = "window.parent.onComplete('error', '" + ex.StackTrace + "');";
			ScriptManager.RegisterStartupScript(this, typeof(Tools_ContentUploadX), "progress", js, true);
		}
	}
}
